class ImageController < ApplicationController
  layout "main", :except => [:edit, :delete, :delete_reason]
  before_filter :login_required, :except => [:show, :list, :random, :index, :search, :json_menu]
  require_role ['Administrator', 'Moderator', 'Uploader'], :only => [:create, :new]
  require_role ['Administrator', 'Moderator'], :only => [:destroy, :edit, :update], :unless => "current_user.id == Image.find(params[:id]).user_id"
  require_role ['Administrator', 'Moderator'], :only => [:undestroy]
  def index
    @imagetags = Image.tag_counts(:order => 'count desc', :limit => 25, :conditions => 'deleted_at is NULL')
    @imagesbyrating = Image.find(:all, :limit => 10, :order => 'rating desc', :conditions => 'deleted_at is NULL')
    @imagesbyviews = Image.find(:all, :limit => 10, :include => :viewing, :order => 'viewings.views desc', :conditions => 'deleted_at is NULL')
    @imageslatest = Image.find(:all, :limit => 10, :order => 'created_at desc', :conditions => 'deleted_at is NULL')
    @imagesrandom = Image.find(:all, :limit => 10, :order => 'RAND()', :conditions => 'deleted_at is NULL')
  end
  
  def new
    @image = Image.new
  end
  
  def json_menu
    categories = []
    Category.find(:all).each do |category|
      categories << {
          "name" => category.name,
          "url" => url_for({:controller => 'image', :action => 'list', :category => category.id, :permalink => category.permalink}),
          "subnav" => nil
        }
    end
    json_array = {
      "config"=>{
        "paddingRight"=>10,
        "rightArrow"=>"/images/bg_menu_right_arrow.gif",
        "linkPaddingTopBottom"=>2,
        "popupBorderSize"=>1,
        "backgroundHover"=>"#D9E1E5 url(/images/nav.gif) left bottom",
        "background"=>"#D9E1E5 url(/images/nav.gif)",
        "popupWidth"=>140,
        "popupPaddingRight"=>10,
        "fontSize"=>12,
        "lineHeight"=>26,
        "borderSizeBottom"=>0,
        "borderSizeRight"=>1,
        "border"=>"solid #AFBEC7",
        "padding"=>5,
        "downArrow"=>"/images/bg_menu_down_arrow.gif",
        "popupLineHeight"=>25,
        "marginBottom"=>5,
        "linkPaddingLeftRight"=>5,
        "borderSizeTop"=>0,
        "popupPadding"=>5,
        "fontColor"=>"#456",
        "borderSizeLeft"=>0,
        "width"=>120
      },
      "menus"=> [
        {
          "name"=>"Random Image",
          "url"=>url_for({:controller => '/image', :action => 'random'}),
          "subnav"=>nil
        },
        {
          "name"=>"Browse Images",
          "url"=>url_for({:controller => '/image', :action => 'list'}),
          "subnav"=>nil
        },
        {
          "name"=>"Categories",
          "url"=>"",
          "subnav"=> categories
        }
      ]
    }
    render :text => 'menuJSON = '+json_array.to_json
  end
  
  def create
    params[:image][:user_id]=current_user.id
    @image = Image.new(params[:image])
    @image.tag_list = params[:image][:tag_list]
    if @image.save
      params[:image_file][:image_id]=@image.id
      sleep 1
      @image_file = ImageFile.new(params[:image_file])
      sleep 1
      if @image_file.save
        flash[:notice] = 'Image was successfully created.'
        redirect_to :action => :show, :id => @image.id, :permalink => @image.permalink
      else
        @image = Image.find(@image.id)
        @image.destroy
        flash[:warning] = 'Image could not be saved.'
        render :action => :new
      end
    else
      render :action => :new
    end
  end
  
  def show
    @image = Image.find(params[:id])
    @image.increment_views
    @page_title = clean_text(@image.title)
    if logged_in? and current_user.has_role?(['Administrator', 'Moderator'])
      @comments = Comment.find(:all, :conditions => ["image_id = ?", params[:id]], :order => 'root_id asc, lft')
    else
      @comments = Comment.find(:all, :conditions => ["image_id = ? and deleted_at is null and purged_at is null", params[:id]], :order => 'root_id asc, lft')
    end
    @comment_threshold = -4
  end
  
  def preview
    @content = params[:content]
    render :partial => "preview"
  end

  def change_rating
    if current_user
      @image = Image.find(params[:id], :include => [:image_rating_logs])
      if has_not_rated_image?(@image)
        if params[:direction] == "down"
          new_rating = @image[:rating] - 1
          @image.update_attributes(:rating => new_rating)
          ImageRatingLog.new(:user_id => current_user.id, :image_id => @image[:id], :value => '-1').save
        else
          if params[:direction] == "up"
            new_rating = @image[:rating] + 1
            @image.update_attributes(:rating => new_rating)
            ImageRatingLog.new(:user_id => current_user.id, :image_id => @image[:id], :value => '1').save
          end
        end
      end
    end
    @image = Image.find(params[:id], :include => [:image_rating_logs])
    render(:partial => 'rating')
  end
  def delete
    @image = Image.find(params[:id])
  end
  def delete_reason
    @image = Image.find(params[:id])
  end
  def destroy
    @image = Image.find(params[:id])
    if @image.update_attributes(:deleted_by => current_user.id, :deleted_at => Time.now(), :deleted_reason => params[:image][:deleted_reason])
      flash[:notice] = 'Image was successfully deleted.'
      redirect_back_or_default :controller => '/image', :action => 'show', :id => params[:id], :permalink => @image.permalink
    else
      flash[:notice] = 'Comment was not deleted.'
      redirect_back_or_default :controller => '/image', :action => 'show', :id => params[:id], :permalink => @image.permalink
    end
  end
  def undestroy
    @image = Image.find(params[:id])
    if @image.update_attributes(:deleted_by => nil, :deleted_at => nil, :deleted_reason => nil)
      flash[:notice] = 'Image was successfully undeleted.'
      redirect_back_or_default :controller => '/image', :action => 'show', :id => params[:id], :permalink => @image.permalink
    else
      flash[:notice] = 'Comment was not undeleted.'
      redirect_back_or_default :controller => '/image', :action => 'show', :id => params[:id], :permalink => @image.permalink
    end
  end
  def edit
    @image = Image.find(params[:id])
  end
  def update
    @image = Image.find(params[:id])
    @image.tag_list = params[:image][:tag_list]
    if request.post?
      if @image.update_attributes(:description => params[:image][:description], :category_id => params[:image][:category_id], :title => params[:image][:title])
        flash[:notice]="Image Updated"
        redirect_back_or_default :controller => '/image', :action => :show, :id => @image.id, :permalink => @image.permalink
      else
        render :action => :edit
      end
    end
  end
  def list
    @per_page = 15
    if params[:category].nil?
      @images = Image.find(:all, :conditions => 'deleted_at is NULL')
      @pages, @images = paginate(:images, {:conditions => 'deleted_at is NULL', :order => 'rating desc, created_at desc', :per_page => @per_page})
    else
      @category = Category.find(params[:category])
      @page_title = @category.name
      @images = Image.find(:all, :conditions => ['deleted_at is NULL and category_id = ?', params[:category]])
      @pages, @images = paginate(:images, {:conditions => ['deleted_at is NULL and category_id = ?', params[:category]], :order => 'rating desc, created_at desc', :per_page => @per_page})
    end
  end
  def search
    if !params[:query].nil?
      @query={:query=>params[:query]}
      @search_query = params[:query]
      @total, @images = Image.full_text_search(@search_query, :page => (params[:page]||1), :conditions => 'deleted_at is NULL')
      @pages = pages_for(@total)
    elsif !params[:tag].nil?
      @page_title = params[:tag].capitalize
      @per_page = 15
      @query={:tag=>params[:tag]}
      @tag = params[:tag]
      @tags = params[:tag].split.map {|o| CGI::unescape(o)}
      @images = Image.find_tagged_with(@tags)
      @pages, @images = paginate(:images, {:conditions => ['tags.name = ? and deleted_at is NULL', @tag], :order => 'rating desc, images.created_at desc', :include => [:tags], :per_page => @per_page})
    else
      flash[:notice] = 'Please enter a search term.'
    end
  end
  def random
    @image = Image.find(:first, :conditions => 'deleted_at is NULL', :order => 'RAND()')
    if (!@image.nil?)
      redirect_to :controller => 'image', :action => 'show', :id => @image.id, :permalink => @image.permalink
    else
      redirect_to :controller => 'image', :action => 'index'
    end
  end
end
